﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;
using CNVP.Config;
using CNVP.Framework.Utils;
using CNVP.JShop;

namespace CNVP.JShop.Publish
{
    /// <summary>
    /// 定义类型
    /// </summary>
    public enum TempType
    {
        Index,
        Column,
        Detail
    }
    /// <summary>
    /// 模板类
    /// </summary>
    public class Template
    {
        /// <summary>
        /// 模板路径
        /// </summary>
        public string TemplatePath { get; set; }

        public int TemplateType { get; set; }
        /// <summary>
        /// 模板类型(0首页，1，2新闻，3商品)
        /// </summary>
        public int ModuleType { get; set; }
        /// <summary>
        /// 模板内容
        /// </summary>
        public string TemplateContent { get; set; }
        /// <summary>
        /// 模板最终内容
        /// </summary>
        public string TemplateFinallyContent { get; set; }
        /// <summary>
        /// 是否发布(True发布，Flase预览)
        /// </summary>
        public bool TemplatePublish { get; set; }
        /// <summary>
        /// 方案名称(当前使用)
        /// </summary>
        public string ProjectName { get; set; }
        /// <summary>
        /// 栏目序号
        /// </summary>
        public string ColumnID { get; set; }
        /// <summary>
        /// 内容序号
        /// </summary>
        public int DetailID { get; set; }
        /// <summary> 
        /// 转换模板所有的标签
        /// </summary>
        public void ReplaceLabels()
        {
            #region "正则属性"
            RegexOptions options = RegexOptions.None;
            Regex[] r = new Regex[10];
            r[0] = new Regex(@"<!--unit name=""(\w+)""-->([\s\S]*?)<!--/unit-->", options);
            r[1] = new Regex(@"\[NT:UnLoop,[^\]]+\][\s\S]*?\[/NT:UnLoop\]|\[NT:Loop,[^\]]+\][\s\S]*?\[/NT:Loop\]", options);
            #endregion
            #region "自定义标签"
            foreach (Match m in r[0].Matches(TemplateContent))
            {
                string _UnitName = m.Groups[1].ToString();
                UnitLabel lb = new UnitLabel();

                lb.ModuleType = TemplateType;
                lb.TemplatePublish = TemplatePublish;
                lb.ProjectName = ProjectName;
                lb.UnitName = _UnitName;
                string _finallyHTML = lb.ParseLabelConetent();
                TemplateContent = TemplateContent.Replace(m.Groups[0].ToString(), _finallyHTML);
            }
            #endregion
            foreach (Match m in r[1].Matches(TemplateContent))
            {
                string Content = m.Value;
                LabelMass lm = new LabelMass(Content, ColumnID);
                lm.ParseContent();
                string s = lm.Parse();
                TemplateContent = TemplateContent.Replace(Content, s);
                string content = m.Value;
            }
            #region "替换常量"
            TemplateContent = TemplateContent.Replace("{#SiteName}", UIConfig.SiteName);
            TemplateContent = TemplateContent.Replace("{#InstallDir}", UIConfig.InstallDir);
            TemplateContent = TemplateContent.Replace("{#TemplateName}", UIConfig.TemplateDir);
            TemplateContent = TemplateContent.Replace("{#ShopLogo}", UIConfig.InstallDir + "UploadFile/Logo/" + UIConfig.Logo);
            TemplateContent = TemplateContent.Replace("{#ShopCarAmount}", new BLL.BLLShoppingCar().GetShopCarCount().ToString());
            TemplateContent = TemplateContent.Replace("{#TCP}", UIConfig.SiteICP);
            TemplateContent = TemplateContent.Replace("{#KeyWords}", UIConfig.KeyWords);
            #endregion
        }
        public void ReplaceLabels(bool canEdit)
        {
            #region "正则属性"
            RegexOptions options = RegexOptions.None;
            Regex[] r = new Regex[10];
            r[0] = new Regex(@"<!--unit name=""(\w+)""-->([\s\S]*?)<!--/unit-->", options);
            r[1] = new Regex(@"\[NT:UnLoop,[^\]]+\][\s\S]*?\[/NT:UnLoop\]|\[NT:Loop,[^\]]+\][\s\S]*?\[/NT:Loop\]", options);
            #endregion
            #region "自定义标签"
            foreach (Match m in r[0].Matches(TemplateContent))
            {
                string _UnitName = m.Groups[1].ToString();
                UnitLabel lb = new UnitLabel();
                lb.ModuleType = TemplateType;
                lb.TemplatePublish = TemplatePublish;
                lb.ProjectName = ProjectName;
                lb.UnitName = _UnitName;
                string _finallyHTML = lb.ParseLabelConetent(canEdit);
                TemplateContent = TemplateContent.Replace(m.Groups[0].ToString(), _finallyHTML);
            }
            #endregion
            foreach (Match m in r[1].Matches(TemplateContent))
            {
                string Content = m.Value;
                LabelMass lm = new LabelMass(Content, ColumnID, DetailID.ToString());
                lm.ParseContent();
                string s = lm.Parse();
                TemplateContent = TemplateContent.Replace(Content, s);
                string content = m.Value;
            }
            #region "栏目信息替换"
            DataTable dt= new DataTable();
            if (!String.IsNullOrEmpty(ColumnID) && ColumnID != "0" && Framework.Utils.Public.IsNumber(ColumnID))
            {
                dt = new CNVP.JShop.BLL.CNVP_Column().GetColumnInfoForTemplate(Convert.ToInt16(ColumnID));
            }
            else if (canEdit)
            {
                dt = new CNVP.JShop.BLL.CNVP_Column().GetTopColumnInfo(ModuleType);
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                #region "商品、新闻具体内容替换"
                DataTable dtDetail = new DataTable();
                if (ModuleType == 3)
                {
                    if (canEdit)
                    {
                        dtDetail = new CNVP.JShop.BLL.CNVP_Products().GetTopProductForTemplate();
                    }
                    else
                    {
                        dtDetail = new CNVP.JShop.BLL.CNVP_Products().GetSingleProductForTemplate(DetailID);
                    }

                    if (dtDetail != null && dtDetail.Rows.Count > 0)
                    {
                        #region "添加浏览记录"
                        HttpCookie historyShow = HttpContext.Current.Request.Cookies["History"];
                        if (historyShow != null && !String.IsNullOrEmpty(historyShow.Value) && Public.IsNumericSet(historyShow.Value))
                        {
                            String[] a = historyShow.Value.Split(',');
                            Int32 indexOfHistory = Array.IndexOf(a, DetailID.ToString());
                            if (historyShow.Value != DetailID.ToString() && indexOfHistory == -1)
                            {
                                HttpContext.Current.Response.Cookies["History"].Value = DetailID.ToString() + "," + historyShow.Value;
                                HttpContext.Current.Response.Cookies["History"].Expires = DateTime.Now.AddDays(30);
                            }
                        }
                        else
                        {
                            HttpContext.Current.Response.Cookies["History"].Value = DetailID.ToString();
                            HttpContext.Current.Response.Cookies["History"].Expires = DateTime.Now.AddDays(30);
                        }
                        #endregion

                        TemplateContent = TemplateContent.Replace("{#ProductID}", dtDetail.Rows[0]["ProductID"].ToString());
                        TemplateContent = TemplateContent.Replace("{#ProductName}", dtDetail.Rows[0]["ProductName"].ToString());
                        TemplateContent = TemplateContent.Replace("{#Intro}", dtDetail.Rows[0]["Intro"].ToString());
                        TemplateContent = TemplateContent.Replace("{#Detail}", dtDetail.Rows[0]["Detail"].ToString());
                        TemplateContent = TemplateContent.Replace("{#MarketPrice}", dtDetail.Rows[0]["MarketPrice"].ToString());
                        TemplateContent = TemplateContent.Replace("{#TradePrice}", dtDetail.Rows[0]["TradePrice"].ToString());
                        TemplateContent = TemplateContent.Replace("{#ProductCode}", dtDetail.Rows[0]["ProductCode"].ToString());
                        TemplateContent = TemplateContent.Replace("{#UpTime}", dtDetail.Rows[0]["UpTime"].ToString());
                        TemplateContent = TemplateContent.Replace("{#EditTime}", dtDetail.Rows[0]["EditTime"].ToString());
                        TemplateContent = TemplateContent.Replace("{#ProductUnit}", dtDetail.Rows[0]["ProductUnit"].ToString());
                        TemplateContent = TemplateContent.Replace("{#ProductWeight}", dtDetail.Rows[0]["ProductWeight"].ToString());
                        TemplateContent = TemplateContent.Replace("{#CostPrice}", dtDetail.Rows[0]["CostPrice"].ToString());
                        TemplateContent = TemplateContent.Replace("{#ImgProLoad}", dtDetail.Rows[0]["ImgProLoad"].ToString());
                        TemplateContent = TemplateContent.Replace("{#SmallPic}", dtDetail.Rows[0]["SmallPic"].ToString());
                        TemplateContent = TemplateContent.Replace("{#BigPic}", dtDetail.Rows[0]["BigPic"].ToString());
                        TemplateContent = TemplateContent.Replace("{#Pic}", dtDetail.Rows[0]["Pic"].ToString());
                        TemplateContent = TemplateContent.Replace("{#ProTypeName}", dtDetail.Rows[0]["ProTypeName"].ToString());
                        TemplateContent = TemplateContent.Replace("{#OriginTitle}", dtDetail.Rows[0]["OriginTitle"].ToString());
                        TemplateContent = TemplateContent.Replace("{#OriginKey}", dtDetail.Rows[0]["OriginKey"].ToString());
                        TemplateContent = TemplateContent.Replace("{#BrankName}", dtDetail.Rows[0]["BrankName"].ToString());
                        TemplateContent = TemplateContent.Replace("{#OriginDescription}", dtDetail.Rows[0]["OriginDescription"].ToString());
                        TemplateContent = TemplateContent.Replace("{#ProductState}", dtDetail.Rows[0]["ProductState"].ToString());
                        TemplateContent = TemplateContent.Replace("{#standardIDs}", dtDetail.Rows[0]["standardIDs"].ToString());
                        TemplateContent = TemplateContent.Replace("{#StockTotalNum}", dtDetail.Rows[0]["StockTotalNum"].ToString());

                        if (!(dtDetail.Rows[0]["AllowReview"] is DBNull) && dtDetail.Rows[0]["AllowReview"].ToString() == "1")
                        {
                            TemplateContent = TemplateContent.Replace("{#Review}", @"<iframe id='frame_content' src='/Controls/GetReviewList.aspx?ID=" + dtDetail.Rows[0]["ProductID"].ToString() + @"' frameborder='0' width='100%' height='200px'></iframe>");
                        }
                        else
                        {
                            TemplateContent = TemplateContent.Replace("{#Review}", "");
                        }

                        #region 评分

                        var bll_ReviewAll = new BLL.CNVP_Review().GetAll_CNVP_Review(DetailID);
                        if (bll_ReviewAll.Count > 0)
                        {
                            int AllRate = bll_ReviewAll.Count;
                            //好评
                            var bll_Review_top = new BLL.CNVP_Review().GetAll_CNVP_Review(DetailID, "4,5");
                            int topRate = bll_Review_top.Count;
                            double rateStatus_Top = topRate / (double)AllRate * 100;
                            TemplateContent = TemplateContent.Replace("{#topRate}", Convert.ToString(Math.Round(rateStatus_Top, 2)));
                            //中评
                            var bll_Review_mid = new BLL.CNVP_Review().GetAll_CNVP_Review(DetailID, "2,3");
                            int midRate = bll_Review_mid.Count;
                            double rateStatus_Mid = midRate / (double)AllRate * 100;
                            TemplateContent = TemplateContent.Replace("{#midRate}", Convert.ToString(Math.Round(rateStatus_Mid, 2)));
                            //差评
                            var bll_Review_button = new BLL.CNVP_Review().GetAll_CNVP_Review(DetailID, "1");
                            int buttonRate = bll_Review_button.Count;
                            double rateStatus_Button = buttonRate / (double)AllRate * 100;
                            TemplateContent = TemplateContent.Replace("{#buttonRate}", Convert.ToString(Math.Round(rateStatus_Button, 2)));
                        }
                        else
                        {
                            TemplateContent = TemplateContent.Replace("{#topRate}", "0");
                            TemplateContent = TemplateContent.Replace("{#midRate}", "0");
                            TemplateContent = TemplateContent.Replace("{#buttonRate}", "0");
                        }
                        #endregion
                        #region 配送说明
                        int _DeliveryFreightID = Convert.ToInt32(string.IsNullOrEmpty(dtDetail.Rows[0]["DeliveryFreightID"].ToString()) ? "0" : dtDetail.Rows[0]["DeliveryFreightID"]);
                        if (_DeliveryFreightID != 0)
                        {
                            var model_Column = new CNVP.JShop.BLL.CNVP_Column().GetSingle_CNVP_ColumnById(_DeliveryFreightID);
                            if (model_Column != null)
                            {
                                TemplateContent = TemplateContent.Replace("{#DeliveryFreightText}", model_Column.Text);
                            }
                        }
                        else
                        {
                            TemplateContent = TemplateContent.Replace("{#DeliveryFreightText}", String.Empty);
                        }
                        #endregion
                    }
                    else
                    {
                        TemplateContent = TemplateContent.Replace("{#ProductID}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#ProductName}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#Intro}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#Detail}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#MarketPrice}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#TradePrice}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#ProductCode}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#UpTime}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#EditTime}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#ProductUnit}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#ProductWeight}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#CostPrice}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#ImgProLoad}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#SmallPic}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#BigPic}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#Pic}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#ProTypeName}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#OriginTitle}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#OriginKey}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#BrankName}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#OriginDescription}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#ProductState}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#Review}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#standardIDs}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#StockTotalNum}", String.Empty);
                    }
                }
                if (ModuleType == 2)
                {
                    if (canEdit)
                    {
                        dtDetail = new CNVP.JShop.BLL.CNVP_NewsInfo().GetTopNewsForTemplate();
                    }
                    else
                    {
                        dtDetail = new CNVP.JShop.BLL.CNVP_NewsInfo().GetSingleNewsForTemplate(DetailID);
                    }

                    if (dtDetail != null && dtDetail.Rows.Count > 0)
                    {
                        TemplateContent = TemplateContent.Replace("{#NewsID}", Convert.ToString(dtDetail.Rows[0]["NewsID"]));
                        TemplateContent = TemplateContent.Replace("{#NewsClassID}", Convert.ToString(dtDetail.Rows[0]["NewsClassID"]));
                        TemplateContent = TemplateContent.Replace("{#NewsTitle}", Convert.ToString(dtDetail.Rows[0]["NewsTitle"]));
                        TemplateContent = TemplateContent.Replace("{#NewsContent}", Convert.ToString(dtDetail.Rows[0]["NewsContent"]));
                        TemplateContent = TemplateContent.Replace("{#AddTime}", Convert.ToString(dtDetail.Rows[0]["AddTime"]));
                        TemplateContent = TemplateContent.Replace("{#UpdateTime}", Convert.ToString(dtDetail.Rows[0]["UpdateTime"]));
                        TemplateContent = TemplateContent.Replace("{#OriginTitle}", Convert.ToString(dtDetail.Rows[0]["OriginTitle"]));
                        TemplateContent = TemplateContent.Replace("{#OriginKey}", Convert.ToString(dtDetail.Rows[0]["OriginKey"]));
                        TemplateContent = TemplateContent.Replace("{#OriginDescription}", Convert.ToString(dtDetail.Rows[0]["OriginDescription"]));
                    }
                    else
                    {
                        TemplateContent = TemplateContent.Replace("{#NewsID}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#NewsClassID}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#NewsTitle}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#NewsContent}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#AddTime}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#UpdateTime}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#OriginTitle}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#OriginKey}", String.Empty);
                        TemplateContent = TemplateContent.Replace("{#OriginDescription}", String.Empty);
                    }
                }
                TemplateContent = TemplateContent.Replace("{#ColumnName}", dt.Rows[0]["ColumnName"].ToString());
                TemplateContent = TemplateContent.Replace("{#ColumnText}", dt.Rows[0]["Text"].ToString());
                TemplateContent = TemplateContent.Replace("{#ColumnTitle}", dt.Rows[0]["OriginTitle"].ToString());
                TemplateContent = TemplateContent.Replace("{#ColumnKeyword}", dt.Rows[0]["Originkey"].ToString());
                TemplateContent = TemplateContent.Replace("{#ColumnDescription}", dt.Rows[0]["OriginDescription"].ToString());
                #endregion
            }
            #endregion

            #region "替换常量"

            TemplateContent = TemplateContent.Replace("{#SiteName}", UIConfig.SiteName);
            TemplateContent = TemplateContent.Replace("{#InstallDir}", UIConfig.InstallDir);
            TemplateContent = TemplateContent.Replace("{#TemplateName}", UIConfig.TemplateDir);
            TemplateContent = TemplateContent.Replace("{#ShopLogo}", UIConfig.InstallDir + "UploadFile/Logo/" + UIConfig.Logo);
            TemplateContent = TemplateContent.Replace("{#ShopCarAmount}", new BLL.BLLShoppingCar().GetShopCarCount().ToString());
            TemplateContent = TemplateContent.Replace("{#TCP}", UIConfig.SiteICP);
            TemplateContent = TemplateContent.Replace("{#KeyWords}", UIConfig.KeyWords);
            #endregion
        }
    }
}
